<?php

/*
 * class weibo
 * 测试账号：http://t.sina.com.cn/2097301057
 * @cokeetang001 13632241880@163.com
*/
require_once ('OAuth.cls.php');

class weibo extends OAuth {
    
    var $format = 'json';
    
    var $apiBaseUrl = 'http://api.t.sina.com.cn/';
    
    var $require_token_url = "http://api.t.sina.com.cn/oauth/request_token";
    
    var $signMethod = 'HMAC-SHA1';

    ///发微博
    
    ///支持280个字母空格 140个汉字

    
    ///有时会不行，可以尝试重试机制

    
    function update($status, $pic = NULL, $in_reply_to_status_id = NULL, $geo = array(
) , $annotations = NULL) {
	$status = trim($status);
	
	if ($status == '') return FALSE;
	$params = array();
	$params['status'] = $status; //z暂时不支持？之类的特殊字符

	
	if ($pic == NULL) {
	    $url = $this->apiBaseUrl . 'statuses/update.' . $this->format;
	    $multi = FALSE;
	} else {
	    $url = $this->apiBaseUrl . 'statuses/upload.' . $this->format;
	    $params['pic'] = $pic;
	    $multi = TRUE;
	    
	    if ($in_reply_to_status_id != NULL) {
		$params['in_reply_to_status_id'] = $in_reply_to_status_id;
	    }
	    
	    if ($annotations != NULL) {
		$params['annotations'] = $annotations;
	    }
	}
	
	if (!empty($geo)) {
	    
	    if (count($geo) != 2) return FALSE; ///geo error

	    $params['lat'] = isset($geo['lat']) ? $geo['lat'] : $geo[0];
	    $params['long'] = isset($geo['long']) ? $geo['long'] : $geo[1];
	}
	return $this->oauthRequire($url, $params, 'post', $multi);

	//var_dump($params);//未urlencode
	
    }

    //0 共有 1 私有
    
    function getUserList($uid, $listType = 0, $cursor = - 1) {

	$url = $this->apiBaseUrl . $uid . '/lists.' . $this->format;
	$params = array();
	
	if ($cursor != - 1) {
	    $params['cursor'] = $cursor;
	}
	
	if ($listType != 0) {
	    $params['listType'] = $listType;
	}

	//$params['source']=$this->appKey;
	return $this->oauthRequire($url, $params, 'get');
    }

    //0 共有 1 私有
    
    function createUserList($uid, $listName, $listType = 1, $description = NULL) {

	$url = $this->apiBaseUrl . $uid . '/lists.' . $this->format;
	
	if (trim__($listName) == '') {
	    throw new ArgException('listName');

	    //argCheck($listName);
	    
	}
	$params = array();
	$params['name'] = $listName;
	
	if ($listType == 0) {
	    $params['mode'] = 'public';
	} elseif ($listType == 1) {
	    $params['mode'] = 'private';
	}
	
	if (!empty($description)) {
	    $params['description'] = $description;
	}
	return $this->oauthRequire($url, $params);
    }
    /**
     *  获取所有给关注列表
     */
    
    function getAllFrineds($uid = NULL, $screenName = NULL) {

	$cursorStart = - 1;
	$count = 100;
	$next_cursor = TRUE;
	$args = array(
	    $uid,
	    $screenName
	);
	array_push($args, $cursorStart);
	array_push($args, $count);
	$users = array();
	while ($next_cursor) {
	    $list = call_user_func_array(array(
		$this,
		'getFriends'
	    ) , $args);
	    $users = array_merge($users, $list['users']);
	    $args[2] = $next_cursor = $list['next_cursor'];
	}
	return array(
	    'users' => $users,
	    'next_cursor' => 0,
	    'previous_cursor' => 1
	);
    }
    /**
     *  仅上传图片
     *
     */
    
    function upload_pic($pic_path) {

	$maxsize = 1 * 1024 * 1024;
	$size = filesize($pic_path);

	//JPEG, GIF, PNG
	list($width, $height, $type) = getimagesize($pic_path);
	
	if ($size <= $maxsize && in_array($type, array(
	    0,
	    1,
	    2
	))) {
	    $url = $this->apiBaseUrl . 'statuses/upload_pic.' . $this->format;
	    $params = array();

	    //$pic=file_get_contents($pic_path);
	    
	    //$fobj=fopen($pic_path,'r');

	    $params['pic'] = '@' . $pic_path;

	    //var_dump($this);
	    return $this->oauthRequire($url, $params, 'post', TRUE);
	} else {

	    //error
	    
	}
    }
    /**
     *  分页获取关注列表
     */
    
    function getFriends($uid = NULL, $screenName = NULL, $cursor = - 1, $count = 20) {

	$url = $this->apiBaseUrl . $uid . '/statuses/friends.' . $this->format;
	$params = array();

	//每页返回的最大记录数 api 限制
	$countMax = 200;
	$countDefault = 20;
	
	if ($uid) $params['user_id'] = $uid;
	
	if ($screenName) $params['screen_name'] = $screenName;
	$params['cursor'] = $cursor;
	
	if ($count != $countDefault) {
	    
	    if ($count > $countMax) $params['count'] = $countMax;
	    else $params['count'] = $count;
	}

	//var_dump($params);
	return $this->oauthRequire($url, $params, 'get');
    }
    /**
     *  获取所有给粉丝列表
     */
    
    function getAllFollowers($uid = NULL, $screenName = NULL) {

	$cursorStart = - 1;
	$count = 100;
	$next_cursor = TRUE;
	$args = array(
	    $uid,
	    $screenName
	);
	array_push($args, $cursorStart);
	array_push($args, $count);
	$users = array();
	while ($next_cursor) {
	    $list = call_user_func_array(array(
		$this,
		'getFollowers'
	    ) , $args);
	    $users = array_merge($users, $list['users']);
	    $args[2] = $next_cursor = $list['next_cursor'];
	}
	return array(
	    'users' => $users,
	    'next_cursor' => 0,
	    'previous_cursor' => 1
	);
    }
    /**
     *  分页获取粉丝列表
     */
    
    function getFollowers($uid = NULL, $screenName = NULL, $cursor = - 1, $count = 20) {

	$url = $this->apiBaseUrl . $uid . '/statuses/followers.' . $this->format;
	$params = array();

	//每页返回的最大记录数 api 限制
	$countMax = 200;
	$countDefault = 20;
	
	if ($uid) $params['user_id'] = $uid;
	
	if ($screenName) $params['screen_name'] = $screenName;
	$params['cursor'] = $cursor;
	
	if ($count != $countDefault) {
	    
	    if ($count > $countMax) $params['count'] = $countMax;
	    else $params['count'] = $count;
	}

	//var_dump($params);
	return $this->oauthRequire($url, $params, 'get');
    }
    /**
     *  获取用户基本信息
     */
    
    function getUserShow($uid = NULL, $screenName = NULL) {

	$url = $this->apiBaseUrl . '/users/show.' . $this->format;
	$params = array();
	$uid && $params['user_id'] = $uid;
	$screenName && $params['screen_name'] = $screenName;
	return $this->oauthRequire($url, $params, 'get');
    }
    /**
     *  获取头像数据
     */
    
    function parseProfileImage($url2uid, $type = TYPE_IMG_30) {


	//http://tp1.sinaimg.cn/1060209184/180/1300090443/2
	
	//var_dump($url);

	
	if (is_numbic($url)) {
	    return sprintf('http://tp1.sinaimg.cn/%s/%s/%s', $url, $type, date('Ymd', time()));
	}
	return preg_replace("/\/(30|50|180)\//", "/" . $type . "/", $url);
    }
    /**
     *  微博搜索
     */
    
    function statusSearch($q = NULL, $filter_ori = FALSE, $filter_pic = NULL, $fuid = FALSE, $province = NULL,$city=NULL,$starttime=NULL,$endtime=NULL,$page=NULL,$count=NULL,$needcount=TRUE,$base_app=NULL,$callback=FALSE) {
	

    }
    ///微博搜索细化
    
    
    /**
     *  用户搜索
     */
    
    function searchUsers($q, $snick = FALSE, $sdomain = FALSE, $sintro = FALSE, $province = NULL, $city = NULL, $gender = FALSE, $comorsch = NULL, $sort = 1, $page = 1, $count = NULL, $callback = FALSE, $base_app = FALSE) {

	$url = $this->apiBaseUrl . '/users/search.' . $this->format;
	$params = array();
	$countDefault = 10;
	$params['q'] = $q;
	$snick && $params['snick'] = $snick;
	$sdomain && $params['sdomain'] = $sdomain;
	$sintro && $params['sintro'] = $sintro;
	$province && $params['province'] = $province;
	$gender && ($gender = $this->_parseGender($gender)) && $params['gender'] = $gender['char'];
	$comorsch && $params['comorsch'] = $comorsch;
	$params['sort'] = $sort;
	$params['page'] = $page;
	$params['page'] = $page;
	$count && $params['count'] = $countDefault;
	$callback && $params['callback'] = $callback;
	$base_app && $params['base_app'] = $base_app;

	//users/search
	
	//var_dump($params);

	return $this->oauthRequire($url, $params, 'get');
    }
    /**
     *  发送 私信
     *  只能发发给自己的粉丝
     *  direct_messages/new
     *  无需审核就可以发送
     */
    
    function directMessages($targetID = NULL, $targetName = NULL, $text) {

	$url = $this->apiBaseUrl . '/direct_messages/new.' . $this->format;
	$params = array();
	$targetID && $params['user_id'] = $targetID;
	$targetName && $params['screen_name'] = $targetName;
	$params['id'] = $targetID || $targetName;
	
	if (!$params['id']) return FALSE;
	$params['text'] = $text;
	return $this->oauthRequire($url, $params, 'post');
    }
    
    function _parseGender($char) {

	$genderArr = array(
	    'bool' => array(
		TRUE,
		FALSE
	    ) ,
	    'en' => array(
		'male',
		'female'
	    ) ,
	    'cn' => array(
		'男',
		'女'
	    ) ,
	    'char' => array(
		'm',
		'f'
	    )
	);
	foreach ($genderArr as $k => $v) {
	    
	    if (in_array($char, $v)) {
		$kk = array_search($char, $v);
		break;
	    }
	}
	return array(
	    'bool' => $genderArr['bool'][$kk],
	    'en' => $genderArr['en'][$kk],
	    'cn' => $genderArr['cn'][$kk],
	    'char' => $genderArr['char'][$kk]
	);
    }
    
    function _parseErr($msg) {

	
	if (is_array($msg)) $msg = $msg['error'];
	$msg = trim($msg);
	$exp = "/^(\d{5}):Error:\s*([\S\s]+)/";
	
	if (preg_match($exp, $msg, $matchs)) {
	    array_shift($matchs);
	    
	    if (count($matchs) == 2) {
		return array(
		    'code' => $matchs[0],
		    'err' => $matchs[1]
		);
	    }
	    return FALSE;
	}
	return FALSE;
    }

    ///multi 是否是multi content type
    
    function oauthRequire($url, $params, $method = 'post', $multi = FALSE) {

	$params['oauth_token'] = $this->oauth_token_access;
	return parent::oauthRequire($url, $params, $this->appSecret . '&' . $this->oauth_token_secret_access, $method, 'json', $multi);
    }
}
?>